﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace test
{
    public partial class Form1 : Form
    {
        User user = new User();
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            if (CheckInput())
            {
                if (Login())
                {
                    FormRoom form1 = new FormRoom();
                    //传值
                    form1.user = user;
                    form1.Show();
                    this.Hide();
                }
                else
                {
                    MessageBox.Show("登录失败！");
                }
            }
        }

        //非空验证
        private bool CheckInput()
        {
            if (text_username.Text.Trim() == "" || text_password.Text.Trim() == "")
            {
                MessageBox.Show("请输入用户名和密码！");
                return false;
            }
            return true;
        }
        ///登录
        public bool Login()
        {
            bool flag = false;
            String username = text_username.Text.Trim();
            String password = text_password.Text.Trim();
            DBHelper dBHelper = new DBHelper();
            try
            {
                //1.创建sql语句
                String sql = String.Format("select * from user where username='{0}' and password='{1}'", username, password);
                //2.command工具
                MySqlCommand cmd = new MySqlCommand(sql, dBHelper.Connection);
                //3.打开连接
                dBHelper.OpenConnection();
                //4.执行
                MySqlDataReader reader = cmd.ExecuteReader();
                //5.判断
                if (reader.Read())
                {
                    //从数据库获取用户信息并封装到user
                    user.Id = Convert.ToInt32(reader[0]);
                    user.Username = reader[1].ToString();
                    user.Password = reader[2].ToString();
                    flag = true;
                }
            }catch(Exception e)
            {
                MessageBox.Show("发生异常：" + e.Message);
            }
            finally
            {
                dBHelper.CloseConnection();
            }
            return flag;
        }
        //取消事件
        private void btn_cancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void link_Register_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FormRegister form = new FormRegister();
            form.Show();
            this.Hide();
        }
    }
}
